import {Component, Input, ViewEncapsulation,OnDestroy} from "@angular/core";
import {NavigationEnd, Router} from "@angular/router";
import { map, filter, scan } from 'rxjs/operators';
@Component({
    selector:'scroll-manager',
    template:`
        <div *ngIf="showToTop"  [style.opacity]="scrollE.el.nativeElement.children[0].scrollTop>400?0.7:0" (click)="toTop()">
            <span class="icon-toTop"></span>
        </div>
    `,
    encapsulation:ViewEncapsulation.None,
    styles:[`
        scroll-manager div{
            position: fixed;
            bottom: 60px;
            right: 10px;
            width: 2rem;
            height: 2rem;
            transition:all 0.5s;
            font-weight:bolder;
            text-align:center;
            border-radius:1rem;
            background-color:#15c9d7;
            color:white;
            font-size:1rem;
            vertical-align: middle;
        }
    `]
})
export class ToTopComponent implements OnDestroy{
    static locationRecorder:any={};
    @Input() scrollE:any;
    @Input() showToTop:boolean;
    private id:number;
    private scrollPositionSubscription:any;
    ngOnDestroy(){
        delete ToTopComponent.locationRecorder[this.id];
        this.scrollPositionSubscription.unsubscribe();
    }
    ngAfterViewInit(){
        let url=this.router.url;
        this.scrollPositionSubscription=this.router.events.pipe(
            filter(evt=>evt instanceof NavigationEnd && evt.url==url)
        ).subscribe(()=>{
                this.scrollE.el.nativeElement.children[0].scrollTop =ToTopComponent.locationRecorder[this.id];
            });
        //weui-infiniteloader利用_onScroll方法触发无限加载，不缓存此方法会禁止无限加载
        let archieve=this.scrollE._onScroll;
        this.scrollE._onScroll=(evt:any)=>{
            ToTopComponent.locationRecorder[this.id]=this.scrollE.el.nativeElement.children[0].scrollTop;
            archieve.call(this.scrollE,evt);//解决原方法中的this指向
        };
    }
    constructor(private router:Router){
        this.id=new Date().getTime();
    }


    toTop(){
        this.scrollE.el.nativeElement.children[0].scrollTop=0;
    }
}
